package com.ytjj.qmyx.admin.utils;

import com.ytjj.common.exception.ApiException;
import com.ytjj.qmyx.admin.model.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;

@Slf4j
public class UserUtil {

    /**
     * 获取 管理员登录账号
     * @return
     */
    public static String getPrincipal(){
        Admin admin  =  (Admin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin.getEmail();
    }

    /**
     * 获取 管理员登录账号id
     * @return
     */
    public static Integer getAdminId(){
        Admin admin  =  (Admin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin.getId();
    }

    /**
     * 获取 管理员登录信息
     * @return
     */
    public static Admin getAdminData(){
        Admin admin  =  (Admin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin;
    }

    /**
     * 是否超级管理员
     * @return
     */
    public static boolean isAdmin(){
        boolean isadmin=false;
        Admin admin  =  (Admin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        if("admin@admin.com".equals(admin.getEmail())||"admin@yitanjj.com".equals(admin.getEmail())) {
            isadmin=true;
        }
        return isadmin;
    }
    /**
     * 获取管理员信息
     * @return
     */
    public static Admin getAdmin(){
        Admin admin  =  (Admin)SecurityUtils.getSubject().getPrincipal();
        if(admin == null){
            throw new ApiException("获取账号失败！");
        }
        return admin;
    }

    public static Admin getUserInfoBySessionId(String sessionId){
        Admin admin = null;
        try{
            Session se = SecurityUtils.getSecurityManager().getSession(new DefaultSessionKey(sessionId));
            Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            admin = (Admin)coll.getPrimaryPrincipal();
        }catch (UnknownSessionException e) {
            log.error("There is no session with id [{}]", sessionId);
        }catch (Exception e){
            log.error("There is no session with id [{}]", sessionId);
        }
        return admin;
    }

}
